package com.huishu.coupon.utils;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.huishu.commons.exception.BaseException;
import com.huishu.commons.pojo.Result;
import com.huishu.commons.pojo.model.UserDO;
import com.huishu.coupon.fegin.UserFeignClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 上下文
 *
 * @author ljj
 * @date 2021/4/9
 */
@Component
public class AssistantContext {

    private static final TransmittableThreadLocal<UserDO> USER_THREAD_LOCAL = new TransmittableThreadLocal<>();

    private static UserFeignClient userFeignClient;

    @Autowired
    public void setUserFeignClient(UserFeignClient userFeignClient) {
        AssistantContext.userFeignClient = userFeignClient;
    }

    public static void init(String uid) {
        if (StringUtils.isNotEmpty(uid)) {
            Result<UserDO> result = userFeignClient.getUserInfo(Long.valueOf(uid));
            if(!result.getStatus()){
                throw new BaseException("调用userFeignClient.getUserInfo异常！");
            }
            setUser(result.getEntry());
            return;
        }
    }

    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUid() {
        UserDO currentUser = AssistantContext.currentUser();
        if (currentUser == null) {
            return null;
        }
        return currentUser.getId();
    }

    /**
     * 获取当前用户ID
     */
    public static String getStringCurrentUid() {
        UserDO currentUser = AssistantContext.currentUser();
        if (currentUser == null) {
            return null;
        }
        return currentUser.getId().toString();
    }

    public static void setUser(UserDO user) {
        USER_THREAD_LOCAL.set(user);
    }

    public static UserDO currentUser() {
        return USER_THREAD_LOCAL.get();
    }


    public static void removeUser() {
        USER_THREAD_LOCAL.remove();
    }


    public static void remove() {
        removeUser();
    }
}
